package com.medsoft.drpcp;

import io.netty.channel.Channel;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class Server {
	private String nodeName;
	private int connSize;
	private boolean isDisconnected = false;
	private Map<String,Member> members = new HashMap<String,Member>();
	private Random random = new Random();
	
	String[] keys;
	public Map<String,Member> getMembers() {
		return members;
	}
	
	public Server(String nodeName2, int connSize2) {
		this.nodeName = nodeName2;
		this.connSize = connSize2;
	}
	public String getNodeName() {
		return nodeName;
	}
	public void setNodeName(String nodeName) {
		this.nodeName = nodeName;
	}
	public int getConnSize() {
		return connSize;
	}
	public void setConnSize(int connSize) {
		this.connSize = connSize;
	}
	
	public void addMember(Member member) {
		members.put(member.getMemberName(), member);
		keys = members.keySet().toArray(new String[0]);
	}
	
	public void addMember(String address,int port) {
		members.put(address + ":" + port,new Member(address,port));
		keys = members.keySet().toArray(new String[0]);
	}
	
	public void removeMember(String address,int port) {
		members.remove(address + ":" + port);
		keys = members.keySet().toArray(new String[0]);
	}
	
	public int getMemberSize() {
		return this.members.size();
	}
	public boolean isDisconnected() {
		return isDisconnected;
	}
	public void setDisconnected(boolean isDisconnected) {
		this.isDisconnected = isDisconnected;
	}

	public Channel getRandomMember() {
		int i = 0;
		while (i <= keys.length) {
			Member randomValue = members.get(keys[random.nextInt(keys.length)]);
			if(randomValue.isConnected())
				return randomValue.getChannel();
			i++;
		}
		return null;
	}
	
	public static void main(String[] args) {
		Random random = new Random();
		System.out.println(random.nextInt(1));
	}
}
